package com.balloon.gateway.security.handler;


import com.balloon.gateway.comm.ResultVOUtils;
import com.balloon.gateway.redis.RedisUtils;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.buffer.DataBufferFactory;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.server.WebFilterExchange;
import org.springframework.security.web.server.authentication.logout.ServerLogoutSuccessHandler;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.Map;
import java.util.concurrent.TimeUnit;

@Component
public class TokenLogoutSuccessHandler implements ServerLogoutSuccessHandler {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public Mono<Void> onLogoutSuccess(WebFilterExchange exchange, Authentication authentication) {
        return Mono.defer(() -> Mono.just(exchange.getExchange().getResponse()).flatMap(response -> {
            DataBufferFactory dataBufferFactory = response.bufferFactory();
            ObjectMapper objectMapper = new ObjectMapper();
            String json = "";
            try {
                Map<String, String> authUser = objectMapper.readValue(authentication.getPrincipal().toString(),new TypeReference<Map<String, String>>() {});
                RedisUtils redisUtils = new RedisUtils(stringRedisTemplate);
                redisUtils.expire("SYSTEM_USER_INFO:" + authUser.get("username"), 0, TimeUnit.MICROSECONDS);

                json = objectMapper.writeValueAsString(ResultVOUtils.logout_success("登出成功"));
            } catch (JsonProcessingException e) {
                e.printStackTrace();
            }
            return response.writeWith(Mono.just(dataBufferFactory.wrap(json.getBytes())));
        }));

    }
}

